<template>
    <div class="outStock">
        <!-- 动态表单 -->
        <dynamic-form :formDataList='formDataList' @getFormData='getFormData'></dynamic-form>

        <!-- 按钮操作 -->
        <custom-setbtn>
            <template #l_btn>
                <div class="l_btn">
                    <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline"
                        @click="$router.push('/stockManagement/outStock/create')">创建出库单</el-button>
                    <el-button type="text" size="mini" :disabled='isBatchCheck' @click="openDialog('print')">
                        批量打印
                    </el-button>
                    <el-button type="text" size="mini" icon="el-icon-edit-outline" @click="openDialog('editMould')">
                        编辑打印模版</el-button>
                </div>
            </template>
            <template #r_btn>
                <div class="r_btn">
                    <!-- 列配置表格 -->
                    <pop-checkbox :disposeGroup='disposeGroup' @handleChangeDiposeGroup='handleChangeDiposeGroup'></pop-checkbox>
                </div>
            </template>
        </custom-setbtn>

        <!-- 编辑打印模版 -->
        <common-dialog ref='editMould' :width="600" @getTemplate='getTemplate' @handleClose='fileList = []'>
            <template #title>
                <span class="title" style='color: rgba(0,0,0,.85);font-weight: 500;font-size: 14px;'>编辑打印模版</span>
            </template>
            <template #body>
                <div class='describe'>
                    可通过下载系统模版
                    <el-button type="text" size="mini" v-for="(i,index) in mouldTableData.slice(0,2)" :key='i.id'
                        @click="getDownloadTemplate({id:i.id},i.templateName)">
                        {{i.templateName}}
                        <span v-show='index < 1'>，</span>
                    </el-button>
                    <br />
                    根据业务需要编辑、上传新的模版。
                </div>
                <el-table :data="mouldTableData" border style="width: 100%" max-height="180"
                    :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
                    :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}" v-loading="mouldLoading"
                    element-loading-background="rgba(250, 250, 250, 0.5)" element-loading-spinner="el-icon-loading">
                    <el-table-column label="模版">
                        <template slot-scope="scope">
                            <div class='mouldTableData'>
                                <div class='l_mould'>
                                    <span>{{scope.row.templateName}}</span>
                                    <span v-show='!scope.row.templateType'>系统模版</span>
                                </div>
                                <div class='r_mould'>
                                    <el-button type="text" size="mini" @click="getDeleteTemplate(scope.row.id)"
                                        v-show='scope.row.templateType'>删除</el-button>
                                    <el-button type="text" size="mini"
                                        @click="getDownloadTemplate({id:scope.row.id},scope.row.templateName)">下载
                                    </el-button>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <div class='upload'>
                    <el-upload :action="$global.uploadUrl+'/sys/printTemplate/uploadTemplate'" :file-list='fileList'
                        :headers='computedToken' :data='{belongModule:2}' :show-file-list='false'
                        :on-success='fileSuccess' accept='.xlsx,xls' :disabled='mouldTableData.length >= 12'>
                        <el-button size="mini" type="primary" icon='el-icon-upload2' :disabled='mouldTableData.length >= 12'>上传模版</el-button>
                        <span slot="tip" style='margin-left:12px;color:rgb(155, 155, 155)'
                            class='el-icon-warning-outline'>最多上传10个，文件大小不超过1M，格式为.xlsx、.xls</span>
                    </el-upload>
                </div>
            </template>
            <template #footer>
                <span style='width:100%;text-align:center;display:inline-block'>
                    <el-button size="small" @click='$refs.editMould.closeDialog()' style='padding:7px 35px'>完 成
                    </el-button>
                </span>
            </template>
        </common-dialog>

        <!-- 选择模版 -->
        <common-dialog ref='print' :width="550" @handleClose='excelRadio = 0'>
            <template #title>
                <span class="title">选择模版</span>
            </template>
            <template #body>
                <div class='dialogBody' style='padding:20px 15px'>
                    <p class='excel'>Excel模版打印</p>
                    <el-radio-group v-model="excelRadio">
                        <el-radio v-for="(i,index) in mouldTableData" :key='i.id' :label="index">
                            {{i.templateName}}
                            <span class='mould' v-show='!i.templateType'>系统模版</span>
                        </el-radio>
                    </el-radio-group>
                    <span class='printDown'>
                        <el-button type='primary' size="small" @click='excelPrintDown' style='padding:7px 35px'>下载打印
                        </el-button>
                    </span>
                </div>
            </template>
        </common-dialog>

        <!-- 打印模板 -->
        <print-mould ref="printBill" :mouldInfo='mouldInfo'></print-mould>

        <!-- 表格 -->
        <table-list :tableGroup='tableGroup' @getCheckedId='getCheckedId'
            @getPrint='getPrint' :searchForm='formDataList.searchForm' ref='tableList'
            @handlePrint='handlePrint' @getTotal='getTotal'>
        </table-list>
    </div>
</template>

<script>
    import {
        printTemplate,
        deleteTemplate,
        downloadTemplate
    } from '@/api/produceController'
    import {
        stockDetail
    } from '@/api/stockController'
    import {
        productColumns
    } from '@/api/customFieldController'
    import request from '@/utils/request'
    import fileDownload from "js-file-download";
    import tableList from './tableList.vue'
    import dynamicForm from '@/components/dynamicForm'
    import commonDialog from './dialog.vue'
    import printMould from './printMould.vue'
    export default {
        data() {
            return {
                isCollapse: false,
                formDataList: {
                    formGroup: [{
                            label: 'code',
                            name: '出库单号',
                            prop: '',
                            placeholder: '请输入出库单号',
                            key: 'srk'
                        },
                        {
                            label: 'typeOther',
                            name: '出库类型',
                            prop: '',
                            placeholder: '请选择出库类型',
                            key: 'sel',
                            node: {
                                default: '',
                                isRadio: false,
                                options: [{
                                        value: '普通出库',
                                        label: '普通出库'
                                    },
                                    {
                                        value: '采购出库',
                                        label: '采购出库'
                                    },
                                    {
                                        value: '成品出库',
                                        label: '成品出库'
                                    },
                                    {
                                        value: '调拨出库',
                                        label: '调拨出库'
                                    },
                                    {
                                        value: '销售退货出库',
                                        label: '销售退货出库'
                                    },
                                    {
                                        value: '其它出库',
                                        label: '其它出库'
                                    }
                                ]
                            }
                        },
                        {
                            label: ['startTime', 'endTime'],
                            name: '出库时间',
                            prop: '',
                            key: 'cki'
                        },
                        {
                            label: 'comment',
                            name: '备注',
                            prop: '',
                            placeholder: '请输入备注',
                            key: 'srk'
                        },
                    ],
                    searchForm: {
                        code: '',
                        typeOther: '',
                        startTime: '',
                        endTime: '',
                        comment: '',
                        type: 1,
                        page: 1,
                        limit: 10
                    },
                    formSet: true,
                    type: 'stockOut'
                },
                mouldLoading: false,
                printRadio: 0,
                ids: '',
                tableTotal: 0,
                pieceOrBatch: '',
                excelRadio: 0,
                fileList: [],
                mouldTableData: [],
                disposeGroup: [],
                tableGroup:[],
                mouldInfo:{
                    name:'',
                    address:'',
                    currentMobile:'',
                    code:'',
                    productList:[]
                }
            }
        },
        components: {
            dynamicForm,
            tableList,
            commonDialog,
            printMould
        },
        mounted() {
            this.getProductColumns({
                type: 'stockOut'
            }).then(()=>{
                this.$refs.tableList.getStockList(this.formDataList.searchForm)
            })
        },
        computed: {
            computedToken() {
                return {
                    Authorization: localStorage.getItem('token')
                }
            },
            isBatchCheck(){
                return this.ids.length <= 0
            }
        },
        watch:{
            tableTotal(total){
                //当表格数据为空时 列配置和表头无自定义字段信息
                if(total <= 0) {
                    this.tableGroup = this.utils.filterCustomFields(this.tableGroup)
                    this.disposeGroup = this.utils.filterCustomFields(this.disposeGroup)
                }
            }
        },
        methods: {
            getProductColumns: async function(data){
                const res = await productColumns(data)
                if (res.code == 200) {
                    this.disposeGroup = []
                    this.tableGroup = []
                    res.data.map((item, i) => {
                        const key = {
                                index:'80',
                                typeOther:'120',
                                time:'150',
                                createTime:'150',
                                createName:'70'
                            }
                        let width = key[item.name] ?? '180'
                        if (item.state) {
                            this.tableGroup.push({
                                label: item.name,
                                name: item.chineseName,
                                width
                            })
                        }
                        this.disposeGroup.push({
                            label: item.name,
                            name: item.chineseName,
                            state: item.state
                        })
                    })
                }
            },
            //监视复选框值变化
            handleChangeDiposeGroup(disposeGroup) {
                let configureList = []
                configureList = disposeGroup.map(i => {
                    return {
                        name: i.label,
                        chineseName: i.name,
                        state: i.state
                    }
                })
                this.getProductColumns({
                    type: 'stockOut',
                    configureList
                }).then(()=>{
                    this.$refs.tableList.updateTable()
                })
            },
            getTotal(total){
                this.tableTotal = total
            },
            handlePrint(payload) {
                const {id,code} = payload
                this.mouldInfo.code = code
                this.stockDetailFn({
                    id,
                    type:1
                })
            },
            //获取勾选中表格的id
            getCheckedId(ids) {
                this.ids = ids
            },
            //出库单详情
            stockDetailFn: async function(data){
                const res = await stockDetail(data)
                this.mouldInfo.productList = res.data.productList
                this.$refs.printBill.$el.children[0].click()
            },
            //点击查询获取表单数据
            getFormData(val) {
                if (val.typeOther) {
                    let typeOther = ''
                    val.typeOther.forEach(i => {
                        typeOther += i + ','
                    })
                    if (typeOther.length > 0) typeOther = typeOther.substr(0, typeOther.length - 1)
                    val.typeOther = typeOther
                }
                val.page = 1
                this.$refs.tableList.getStockList(val)
            },
            //打开相对应的dialog
            openDialog(way) {
                this.getPrintTemplate({
                    belongModule: 2
                })
                this.$refs[way].openDialog()
            },
            //编辑打印模板列表
            getPrintTemplate(data) {
                this.mouldLoading = true
                printTemplate(data).then(res => {
                    if (res.code == 200) {
                        this.mouldTableData = res.data.records
                    }
                    this.mouldLoading = false
                })
            },
            //删除打印模板
            getDeleteTemplate(data) {
                deleteTemplate(data).then(res => {
                    if (res.code == 200) {
                        this.getPrintTemplate({
                            belongModule: 2
                        })
                        this.utils.showMsg('删除成功', 'success')
                    }
                })
            },
            //下载模板
            getDownloadTemplate(data, templateName) {
                downloadTemplate(data, templateName).then(res => {
                    let index = templateName.indexOf('.')
                    let subName = templateName.slice(0, index)
                    this.utils.showMsg('开始下载', 'success')
                    fileDownload(res, subName + new Date().dateFormat('yyyyMMddhhmmss'),
                        'application/vnd.ms-excel;charset=UTF-8')
                })
            },
            getTemplate(way) {
                this.getPrintTemplate({
                    belongModule: 2
                })
            },
            //上传成功
            fileSuccess() {
                this.getPrintTemplate({
                    belongModule: 2
                })
                this.utils.showMsg('上传成功', 'success')
            },
            //单条数据打印
            getPrint(id) {
                this.ids = id
                this.pieceOrBatch = 'piece'
                this.getPrintTemplate({
                    belongModule: 2
                })
                this.$refs.print.openDialog()
            },
            //批量打印
            batchPrint() {
                this.pieceOrBatch = 'batch'
                this.getPrintTemplate({
                    belongModule: 2
                })
                this.$refs.print.openDialog()
            },
            getUrl(data) {
                return request({
                    responseType: 'blob',
                    url: '/printTemplate/exportDataByModel',
                    method: 'post',
                    data
                })
            },
            getDataList(data, tit) {
                this.getUrl(data).then(res => {
                    this.utils.showMsg('开始下载', 'success')
                    fileDownload(res, tit + new Date().dateFormat('yyyyMMddhhmmss') + '.xlsx',
                        'application/vnd.ms-excel;charset=UTF-8')
                    this.excelRadio = 0
                    this.$refs.print.closeDialog()
                })
            },
            //单条-批量打印功能
            excelPrintDown() {
                let selectTemp = this.mouldTableData.find((i, index) => index == this.excelRadio)
                let payload = this.pieceOrBatch == 'piece' ? {
                    id: selectTemp.id,
                    workId: this.ids
                } : {
                    id: selectTemp.id,
                    workIds: this.ids
                }
                let index = selectTemp.templateName.indexOf('.')
                let subName = selectTemp.templateName.slice(0, index)
                this.getDataList(payload, subName)
            },
        },
    }
</script>

<style lang="less" scoped>
    .outStock {
        overflow: auto;

        /deep/ th.el-table__cell.gutter {
            background-color: #fafafa;
        }

        /deep/ .el-dialog__body {
            padding: 10px 30px 20px 30px;

            .describe {
                margin-bottom: 10px;

                .el-link.el-link--success {
                    font-size: 12px;
                    color: #02b980;
                    vertical-align: baseline;
                }
            }

            .mouldTableData {
                .l_mould {
                    float: left;

                    span:last-child {
                        margin-left: 8px;
                        color: rgb(153, 153, 153);
                        border: 1px solid rgb(204, 204, 204);
                        border-radius: 2px;
                        padding: 1px 3px
                    }
                }

                .r_mould {
                    float: right;

                    .el-link.el-link--success {
                        font-size: 12px;
                        color: #02b980;
                    }
                }
            }

            .upload {
                margin-top: 20px;
            }

            .dialogBody {
                border: 1px solid #edeef3;
                background: #fbfbfb;
            }

            .el-radio-group {
                display: flex;
                flex-direction: column;
                padding: 15px 0 0 10px;
                margin-bottom: 20px;
                justify-content: space-between;

                .mould {
                    margin-left: 8px;
                    color: rgb(153, 153, 153);
                    border: 1px solid rgb(204, 204, 204);
                    border-radius: 2px;
                    padding: 1px 3px
                }

                .el-radio {
                    display: flex;
                    align-items: center;
                    margin-bottom: 10px;

                    .el-radio__label {
                        padding: 5px 0 5px 8px;
                        width: 300px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                }

                .el-radio:last-child {
                    margin-bottom: 0;
                }
            }

            .el-radio:last-child {
                margin-bottom: 0;
            }

            .printDown {
                display: inline-block;
                width: 100%;
                text-align: center;
            }
        }
    }
</style>